<template>
  <div id="search-condition-top"
       :class="['search-condition-top-default', {'search-condition-expand': isExpand}, {'search-condition-selected': selectedConditionsNumber > 0}]"
       @click="searchConditionTopClicked">
    <span class="xicon-filter"></span>
    <div :class="[selectedConditionsNumber > 0 ? 'search-condition-number-show' : 'search-condition-number-hide']">
      <span>{{ selectedConditionsNumber }}</span>
      <span :class="['search-condition-space', {'search-condition-space-light': isExpand}]">|</span>
      <span class="search-condition-delete"
            @click.stop="deleteAllSelectedCondition">
        <span class="xicon-close search-condition-delete-span"></span>
      </span>
    </div>
  </div>
</template>

<script>
  import searchConditionContainer from './search-condition-container.vue';

  export default {
    props: {
      containerParentId: {
        type: String,
        default: function () {
          return null;
        }
      },
      conditions: {
        type: Array,
        default: () => [
          // {
          //   type: 'RADIO',
          //   title: '单选',
          //   key: '3',
          //   placeholder: '请选择',
          //   items: [
          //     { title: '重要', value: '0' },
          //     { title: '不重要', value: '1' }
          //   ]
          // },
          // {
          //   type: 'CHECKBOX',
          //   title: '复选',
          //   key: '4',
          //   placeholder: '请选择',
          //   items: [
          //     { title: '重要', value: '0' },
          //     { title: '不重要', value: '1' }
          //   ]
          // },
          // {
          //   type: 'INPUT',
          //   title: '输入框',
          //   key: '0',
          //   placeholder: '请输入',
          //   items: []
          // },
          // {
          //   type: 'SELECT',
          //   title: '下拉单选',
          //   key: '1',
          //   placeholder: '请输入',
          //   items: [
          //     {
          //       title: '男',
          //       value: '0'
          //     },
          //     {
          //       title: '女',
          //       value: '1'
          //     }
          //   ]
          // },
          // {
          //   type: 'DATE_MULTI',
          //   title: '范围日期',
          //   key: '2',
          //   placeholder: '请选择',
          //   items: []
          // },
          // {
          //   type: 'INPUT',
          //   title: '标题22',
          //   key: '5',
          //   placeholder: '请输入',
          //   items: []
          // },
          // {
          //   type: 'SELECT_MULTI',
          //   title: '下拉多选',
          //   key: '8',
          //   placeholder: '请输入',
          //   items: [
          //     {
          //       title: '男',
          //       value: '0'
          //     },
          //     {
          //       title: '女',
          //       value: '1'
          //     },
          //     {
          //       title: '2',
          //       value: '2'
          //     },
          //     {
          //       title: '3',
          //       value: '3'
          //     },
          //     {
          //       title: '4',
          //       value: '4'
          //     },
          //     {
          //       title: '5',
          //       value: '5'
          //     },
          //     {
          //       title: '6',
          //       value: '6'
          //     },
          //     {
          //       title: '7',
          //       value: '7'
          //     },
          //     {
          //       title: '8',
          //       value: '8'
          //     },
          //     {
          //       title: '9',
          //       value: '9'
          //     }
          //   ]
          // }
        ]
      }
      // defaultSelectedConditions: {
      //   type: Array,
      //   default: () => []
      // }
    },
    data() {
      const selectedConditions = this.getDefaultSelectedConditions(this.conditions);
      return {
        selectedConditions: selectedConditions,
        isExpand: false,
        conditionContainer: null
      };
    },
    created() {},
    mounted() {
      this.initSearchConditionContainer();
    },
    computed: {
      selectedConditionsNumber() {
        let number = 0;
        this.selectedConditions.map((item) => {
          if (!item.isDefaultValue) {
            number++;
          }
        });

        return number;
      }
    },
    watch: {
      conditions: {
        handler(newVal, oldVal) {
          this.selectedConditions = this.getDefaultSelectedConditions(newVal);
          if (this.conditionContainer) {
            this.conditionContainer.conditions = newVal;
            this.conditionContainer.selectedConditions = this.selectedConditions;
          }
        },
        deep: true
      }
      // defaultSelectedConditions: {
      //   handler(newVal, oldVal) {
      //     this.selectedConditions = this.getDefaultSelectedConditions(newVal);
      //     if (this.conditionContainer) {
      //       this.conditionContainer.selectedConditions = this.selectedConditions;
      //     }
      //   },
      //   deep: true
      // }
    },
    methods: {
      getDefaultSelectedConditions(selectedConditions) {
        const temp = [];
        selectedConditions.map((item) => {
          if (item.key && item.defaultValue && item.defaultValue.value !== undefined) {
            temp.push({
              key: item.key,
              // 默认值只有value属性时，就将value赋值给当前对象value
              value:
                Object.keys(item.defaultValue).length == 1
                  ? item.defaultValue.value
                  : { ...item.defaultValue },
              isDefaultValue: true
            });
          }
        });

        return temp;
      },
      initSearchConditionContainer() {
        if (this.containerParentId && document.getElementById(this.containerParentId)) {
          let container = Vue.extend(searchConditionContainer);
          this.conditionContainer = new container({
            el: document.getElementById(this.containerParentId)
          });
          this.conditionContainer.conditions = this.conditions;
          this.conditionContainer.onConditionValueChange = this.onConditionValueChange;
        } else {
          console.log('缺少 searchConditionContainer 挂载点 ！');
        }
      },
      onConditionValueChange(data, isEmitSearch = true) {
        console.log('----- onConditionValueChange -----', data);
        if (data.value === null) {
          this.deleteSelectedConditionByKey(data.key);
        } else {
          this.addSelectedCondition(data);
        }
        this.conditionContainer.selectedConditions = this.selectedConditions;
        this.emitValueChange(); // 触发值改变事件
        if (isEmitSearch) {
          this.emitSearch(); // 触发搜索事件
        }
      },
      // 通过筛选条件的key，获取筛选条件的详细信息
      getConditionByKey(key) {
        for (let i = 0; i < this.conditions.length; ++i) {
          const item = this.conditions[i];
          if (item.key === key) {
            return item;
          }
        }
      },

      // 通过筛选条件的key，获取筛选条件的默认值
      getConditionDefaultValueByKey(key) {
        let temp = null;
        const condition = this.getConditionByKey(key);
        if (condition && condition.defaultValue && condition.defaultValue.value) {
          // 默认值只有value属性时，就将value赋值给当前对象value
          temp =
            Object.keys(condition.defaultValue).length == 1
              ? condition.defaultValue.value
              : { ...condition.defaultValue };
        }

        return temp;
      },

      // 获取选择的条件集合对象
      getSelectedConditionsObj() {
        const selectedConditionsObj = {};
        for (let i = 0; i < this.selectedConditions.length; ++i) {
          const item = this.selectedConditions[i];
          selectedConditionsObj[item.key] = item.value;
        }

        return selectedConditionsObj;
      },
      // 格式化选择的条件集合对象，方便业务直接使用
      formatSelectedConditionsObj(selectedConditionsObj) {
        let obj = {};
        for (let key in selectedConditionsObj) {
          const value = selectedConditionsObj[key];
          let formatValue = null;
          if (this.conditionContainer) {
            formatValue = this.conditionContainer.getFormatValueByConditionKey(key);
          }

          if (formatValue) {
            obj = { ...obj, ...formatValue };
          } else if (value instanceof Array) {
            obj[key] = value.join(',');
          } else if (value instanceof Object && value.value) {
            obj[key] = value.value;
          } else {
            obj[key] = value;
          }
        }

        // console.log('formatValue:', obj);

        return obj;
      },
      addSelectedCondition(data) {
        const key = data.key;
        // 先判断添加的条件是否有默认值，并且选中的值是否与默认值相等
        data.isDefaultValue = this.isEqualDefaultValueByKey(key, data.value);
        const condition = this.getSelectedConditionByKey(key);
        if (condition) {
          condition.value = data.value;
          condition.isDefaultValue = data.isDefaultValue;
        } else {
          this.selectedConditions.push(data);
        }
      },

      // 判断指定的筛选条件，当前选中的值是否与默认值相同
      isEqualDefaultValueByKey(key, newValue) {
        const defaultValue = this.getConditionDefaultValueByKey(key);
        if (defaultValue === null) return false;

        if (defaultValue == newValue) {
          return true;
        } else if (newValue instanceof Array) {
          // 数组长度不等时，直接返回false
          if (newValue.length != defaultValue.length) {
            return false;
          }
          const obj = {};
          newValue.forEach((element) => {
            obj[element] = true;
          });
          for (let i = 0; i < defaultValue.length; ++i) {
            if (!obj[defaultValue[i]]) {
              return false;
            }
          }
          return true;
        } else if (newValue instanceof Object) {
          let result = true;
          for (let key in newValue) {
            if (newValue[key] != defaultValue[key]) {
              result = false;
              break;
            }
          }
          return result;
        } else {
          return false;
        }
      },
      // 移除选中的条件
      deleteSelectedConditionByKey(key) {
        const condition = this.getSelectedConditionByKey(key);
        const defaultValue = this.getConditionDefaultValueByKey(key);
        if (condition) {
          if (defaultValue !== null) {
            condition.value = defaultValue;
            condition.isDefaultValue = true;
          } else {
            let index = this.selectedConditions.indexOf(condition);
            this.selectedConditions.splice(index, 1);
          }
        }
      },
      // 移除所有的选中条件
      deleteAllSelectedCondition(e) {
        this.selectedConditions = this.getDefaultSelectedConditions(this.conditions);
        this.conditionContainer.selectedConditions = this.selectedConditions;
        this.emitValueChange();
      },
      getSelectedConditionByKey(key) {
        let condition = null;
        for (let i = 0; i < this.selectedConditions.length; ++i) {
          let item = this.selectedConditions[i];
          if (item.key == key) {
            condition = item;
            break;
          }
        }
        return condition;
      },
      searchConditionTopClicked() {
        this.isExpand = !this.isExpand;
        if (this.conditionContainer) {
          this.conditionContainer.isShow = this.isExpand;
        }
        this.$emit('expandChange', this.isExpand);
      },
      emitValueChange() {
        const selectedConditionsObj = this.getSelectedConditionsObj();
        this.$emit(
          'valueChange',
          selectedConditionsObj,
          this.formatSelectedConditionsObj(selectedConditionsObj)
        );
      },
      emitSearch() {
        const selectedConditionsObj = this.getSelectedConditionsObj();
        this.$emit(
          'search',
          selectedConditionsObj,
          this.formatSelectedConditionsObj(selectedConditionsObj)
        );
      }
    }
  };
</script>

<style scoped>
  .search-condition-top-default {
    min-width: 32px;
    height: 30px;
    line-height: 30px;
    background: #ffffff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    color: #595959;
    display: flex;
    flex: 0 0 auto;
    padding: 0px 7px;
    cursor: pointer;
  }
  .search-condition-top-default:hover {
    border-color: #0077ff;
    border-color: var(--theme-brand5, #0077ff);
    color: #0278ff;
    color: var(--theme-brand6, #0278ff);
  }

  .search-condition-expand {
    background: #e6f6ff;
    background: var(--theme-brand1, #e6f6ff);
    border-color: #a3daff;
    border-color: var(--theme-brand2, #a3daff);
    color: #0278ff;
    color: var(--theme-brand6, #0278ff);
  }
  .search-condition-expand:hover {
    border-color: #0077ff;
    border-color: var(--theme-brand5, #0077ff);
  }

  .search-condition-selected {
    color: #0278ff;
    color: var(--theme-brand6, #0278ff);
  }
  .search-condition-space {
    display: block;
    padding: 0px 6px;
    color: #e4e4e4;
  }
  .search-condition-number-show {
    display: flex;
  }
  .search-condition-number-hide {
    display: none;
  }
  .search-condition-space-light {
    color: #a3daff;
    color: var(--theme-brand2, #a3daff);
  }
  .search-condition-delete {
    cursor: pointer;
  }
  .search-condition-delete-span {
    font-size: 12px;
  }
</style>
